package com.ruoyi.procured.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.procured.domain.ProcuredPlan;
import com.ruoyi.procured.domain.ProcuredPlanLog;
import com.ruoyi.procured.domain.ProcuredPlanProcess;
import com.ruoyi.procured.domain.vo.ProcuredPlanProcessVo;
import com.ruoyi.procured.domain.vo.ProcuredPlanVo;
import com.ruoyi.procured.mapper.ProcuredPlanLogMapper;
import com.ruoyi.procured.mapper.ProcuredPlanMapper;
import com.ruoyi.procured.mapper.ProcuredPlanProcessMapper;
import com.ruoyi.procured.service.IProcuredPlanProcessService;
import com.ruoyi.sale.domain.Plan;
import com.ruoyi.sale.domain.PlanProcess;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.template.domain.TemplateDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


/**
 * 申请付款Service业务层处理
 * 
 * @author 刘广帆
 * @date 2025-03-20
 */
@Service
public class ProcuredPlanProcessServiceImpl implements IProcuredPlanProcessService
{
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ProcuredPlanProcessMapper planProcessMapper;

    @Autowired
    private ProcuredPlanLogMapper procuredPlanLogMapper;

    @Autowired
    private ProcuredPlanMapper procuredPlanMapper;
    /**
     * 新增审核流程
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public void insertProcuredPlanProcessQuash(String procuredPlanId, List<TemplateDetail> templateDetails, Long userId) {

        // 1. 删除旧的流程（如果有）
        LambdaQueryWrapper<ProcuredPlanProcess> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(ProcuredPlanProcess::getProcuredPlanId, procuredPlanId);
        planProcessMapper.delete(deleteWrapper);

        //2. 插入新的审核流程
        for(TemplateDetail td : templateDetails){

            String UUID = IdUtils.fastSimpleUUID();
            String processStatus = Constants.PAYMENT_REQUEST_PROCESS_STATUS_PENDING;
            Date processTime = DateUtils.getNowDate();

            Long reviewerId = Long.valueOf(td.getReviewerId());
            SysUser user = sysUserMapper.selectUserById(reviewerId);
            Long reviewerDeptId = user.getDeptId();

            LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserRole::getUserId, reviewerId);
            SysUserRole sur = sysUserRoleMapper.selectOne(queryWrapper);
            if(null == sur){
                throw new ServiceException(user.getNickName()+"未设置角色，请联系人事匹配后再操作。");
            }
            Long reviewerRoleId = sur.getRoleId();

            Integer reviewerOrder = td.getReviewOrder();

            ProcuredPlanProcess pp = new ProcuredPlanProcess(UUID,processStatus,null,procuredPlanId,reviewerId,reviewerDeptId,reviewerRoleId,reviewerOrder);
            planProcessMapper.insert(pp);
        }

        //插入审核流程表日志
        SysUser user =  sysUserMapper.selectUserById(userId);
        saveProcuredPlantLog(procuredPlanId,Constants.SUCCESS,user.getNickName(),"");
    }
    /**
     * 查询审核流程
     * @param procuredPlanId
     * @return
     */
    @Override
    public List<ProcuredPlanProcessVo> getProcuredPlanProcessList(Long procuredPlanId) {
        return planProcessMapper.getProcuredPlanProcessList(procuredPlanId);
    }

    /**
     * 我已审核的采购计划
     * @param procuredPlan
     * @return
     */
    @Override
    public List<ProcuredPlanVo> getPlanReadyProcuredProcessList(ProcuredPlanVo procuredPlan) {
        return planProcessMapper.getPlanReadyProcuredProcessList(procuredPlan);
    }
    /**
     * 我发起的采购计划
     * @param procuredPlan
     * @return
     */
    @Override
    public List<ProcuredPlanVo> getPlanMyProcuredProcessList(ProcuredPlanVo procuredPlan) {
        return planProcessMapper.getPlanMyProcuredProcessList(procuredPlan);
    }
    /**
     * 更新审批结果
     * @param procuredPlanProcess
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProcuredPlanProcessStatus(ProcuredPlanProcess procuredPlanProcess) {
        Long reviewerId = procuredPlanProcess.getReviewerId();
        String planProcessStatus = procuredPlanProcess.getProcessStatus();
        String planProcessRemark = procuredPlanProcess.getProcessRemark();
        String planId = procuredPlanProcess.getProcuredPlanId();

        //更新审核流程表
        LambdaUpdateWrapper<ProcuredPlanProcess> updateWrapper  = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProcuredPlanProcess::getProcuredPlanId,planId);
        updateWrapper.eq(ProcuredPlanProcess::getReviewerId,reviewerId);
        updateWrapper.set(ProcuredPlanProcess::getProcessStatus, planProcessStatus);
        updateWrapper.set(ProcuredPlanProcess::getProcessTime,DateUtils.getNowDate());
        updateWrapper.set(ProcuredPlanProcess::getProcessRemark,planProcessRemark);
        planProcessMapper.update(null,updateWrapper);

        //插入审核流程表日志
        SysUser user =  sysUserMapper.selectUserById(reviewerId);
        saveProcuredPlantLog(planId,planProcessStatus,user.getNickName(),planProcessRemark);

        //汇总状态，更新到采购计划
        List<String> statuses = planProcessMapper.selectStatusesByPlanId(planId);

        String newStatus;
        if (statuses.contains("4")) {
            newStatus =  "4";//Constants.PLAN_PROCESS_STATUS_REJECTED; // 有任何一条为 "0"，则设为驳回状态
        } else if (statuses.stream().allMatch(status -> "1".equals(status))) {
            newStatus = "1";//Constants.PLAN_PROCESS_STATUS_SUCCESS; // 如果所有记录都为 "1"，则设为已审核
        } else {
            newStatus = "5";//Constants.PLAN_PROCESS_STATUS_PENDING; // 0 否则为审核中
        }

        Long reviewerUserId = procuredPlanMapper.selectById(planId).getReviewerUserId();
        if(planProcessStatus.equals("1")){

            LambdaQueryWrapper<ProcuredPlanProcess> qw = new LambdaQueryWrapper<>();
            qw.eq(ProcuredPlanProcess::getProcuredPlanId,planId);
            qw.eq(ProcuredPlanProcess::getReviewerId,reviewerId);
            ProcuredPlanProcess pp = planProcessMapper.selectOne(qw);
            if(pp == null){
                throw new ServiceException("获取审核流程明细失败。");
            }
            Integer reviewerOrder = pp.getReviewerOrder();

            //通过审核，当前审核人换到上一层级
            LambdaQueryWrapper<ProcuredPlanProcess> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProcuredPlanProcess::getProcuredPlanId,planId)
                    .gt(ProcuredPlanProcess::getReviewerOrder,reviewerOrder)
                    .orderByAsc(ProcuredPlanProcess::getReviewerOrder)
                    .last("LIMIT 1");
            ProcuredPlanProcess nextProcess = planProcessMapper.selectOne(queryWrapper);
            if(nextProcess != null){
                reviewerUserId = nextProcess.getReviewerId();
            }

        }
        ProcuredPlan p = new ProcuredPlan();
        p.setPlanId(Long.valueOf(planId));
        p.setPlanStatus(newStatus);
        p.setReviewerUserId(reviewerUserId);
        //更新采购计划表的审核状态
        return procuredPlanMapper.updatePlanReviewStatus(p);
    }

    /**
     * 申请表日志
     * @return
     */
    private void saveProcuredPlantLog(String procuredPlanId, String logStatus, String nickName, String logRemark){
        ProcuredPlanLog log = new ProcuredPlanLog(IdUtils.fastSimpleUUID(),procuredPlanId,
                logStatus,nickName,logRemark,DateUtils.getNowDate());
        procuredPlanLogMapper.insert(log);
    }
}
